package com.fitc.json;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URLConnection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JpegDownloader implements Runnable {

	static DatabaseHelper database;
	Photo photo;

	public JpegDownloader(Photo p) {
		this.photo = p;
	}

	private byte[] downloadImageData() {
		URLConnection urlcon;
		DataInputStream dis;
		byte[] imageData = null; // byte aray used to hold data from downloaded
									// file.
		try {
			urlcon = photo.getUrl().openConnection(); // open the url
														// connection.
			dis = new DataInputStream(urlcon.getInputStream()); // get a data
																// stream from
																// the url
																// connection.
			imageData = new byte[urlcon.getContentLength()]; // determine how
																// many byes the
																// file size is
																// and make
																// array big
																// enough to
																// hold the data
			for (int x = 0; x < imageData.length; x++) { // fill byte array with
															// bytes from the
															// data input stream
				imageData[x] = dis.readByte();
			}

			dis.close(); // close the data input stream

		} catch (MalformedURLException m) {
			System.out.println(m);
		} catch (IOException io) {
			System.out.println(io);
		}
		return imageData;
	}

	private void saveToFileFromDb() {

		String sql = "SELECT image from images where idimage = "
				+ photo.getId();

		try {
			PreparedStatement preparedStatement = database.connection
					.prepareStatement(sql);
			// preparedStatement.setLong(1, photo.getId());
			ResultSet resultSet = preparedStatement.executeQuery(sql);
			Object obj = resultSet;

			while (resultSet.next()) {
				File image = new File("file.jpg");
				FileOutputStream fos = new FileOutputStream(image); // create an
																	// object
																	// representing
																	// the file
																	// we want
																	// to save
				byte[] buffer = new byte[1];
				InputStream inputStream = resultSet.getBinaryStream(1);
				System.out.println(inputStream.available());

				int read = 0;
				byte[] bytes = new byte[1];

				while ((read = inputStream.read(bytes)) != -1) {
					fos.write(bytes, 0, read);
					fos.flush();
				}

				fos.close();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void setDatabase(DatabaseHelper db) {
		database = db;
	}

	private void saveToDb(byte[] imageData) {
		String UPDATE_WITH_JPEG = "update images set image = ? where idimage = ?;";

		PreparedStatement preparedStatement = null;
		try {
			database.connection.setAutoCommit(false);
			preparedStatement = database.connection
					.prepareStatement(UPDATE_WITH_JPEG);
			preparedStatement.setLong(2, photo.getId());
			preparedStatement.setBytes(1, imageData);
			int count = preparedStatement.executeUpdate();

			database.connection.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				preparedStatement.close();
				System.out.println("Downloaded image: " + photo.getId()
						+ " ...");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void run() {

		// download image data from url
		byte[] imageData = downloadImageData();

		// write to database
		saveToDb(imageData);

	}

}
